﻿using System;
using System.Configuration;
using System.ServiceModel;
using System.ServiceProcess;

using BizElements.BusinessLayer;

namespace BizElements.Services.Windows
{
    /// <summary>Entry point for the application.</summary>
    internal static class Program
    {
        /// <summary>The main entry point for the application. Determines whether the application is used as Windows service or as console application (usefull for debugging).</summary>
        /// <param name="args">Optional arguments. If "/c" is specified then the WCF service will be hosted in a console application.</param>
        private static void Main(string[] args)
        {
            bool startAsConsoleApp = (args.Length > 0) && (args[0].ToLowerInvariant() == "/c");
            if (startAsConsoleApp)
                StartConsoleApp();
            else
                ServiceBase.Run(new RpcWinService());
        }

        /// <summary>Starts console app which hosts WCF remoting service.</summary>
        private static void StartConsoleApp()
        {
            RpcWcfServiceManager.Start();
            Console.WriteLine("Press ESC to exit.");
            while (true)
            {
                ConsoleKeyInfo key = Console.ReadKey();
                if (key.Key == ConsoleKey.Escape)
                    break;
            }

            RpcWcfServiceManager.Stop();
        }
    }

    /// <summary>Starts and stops remoting WCF services.</summary>
    internal static class RpcWcfServiceManager
    {
        private static ServiceHostBase RpcServiceHost;
        private static ServiceHostBase LogServiceHost;

        /// <summary>Starts remoting services.</summary>
        public static void Start()
        {
            RpcServiceHost = new ServiceHost(typeof(MethodReceiverService));
            RpcServiceHost.Open();

            LogServiceHost = new ServiceHost(typeof(LogReceiverService));
            LogServiceHost.Open();
        }

        /// <summary>Stops remoting services.</summary>
        public static void Stop()
        {
            if (RpcServiceHost != null)
                RpcServiceHost.Close();

            if (LogServiceHost != null)
                LogServiceHost.Close();
        }
    }
}
